package co.baiku.boot.filter;

import co.baiku.boot.common.message.Message;
import co.baiku.boot.common.tools.JsonTools;
import co.baiku.boot.common.tools.StringTools;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class AjaxRequestFilter extends UserFilter {
    Logger log = LoggerFactory.getLogger(AjaxRequestFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (request instanceof HttpServletRequest) {
            if (HttpMethod.OPTIONS.name().equals(((HttpServletRequest) request).getMethod().toUpperCase())) {
                return true;
            }
        }
        Subject subject = SecurityUtils.getSubject();

        if (null != subject) {
            if (subject.isRemembered()) {
                return Boolean.TRUE;
            }
            if (subject.isAuthenticated()) {
                return Boolean.TRUE;
            }
        }

        return Boolean.FALSE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpResponse;
        httpResponse = WebUtils.toHttp(response);
        WebUtils.saveRequest(request);
        httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpResponse.setCharacterEncoding(StringTools.UTF8.name());
        httpResponse.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = httpResponse.getWriter();
            out.append(JsonTools.beanToJson(Message.fail(HttpStatus.UNAUTHORIZED, "登录信息失效,请重新登录")));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return false;
    }
}
